package com.hsd.survey.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hsd.commons.util.DateUtil;
import com.hsd.core.base.dao.IBaseDAO;
import com.hsd.core.base.service.impl.BaseService;
import com.hsd.survey.dao.ISurveyCommonDao;
import com.hsd.survey.helper.SurveyModelHelper;
import com.hsd.survey.model.HsdDataResult;
import com.hsd.survey.model.HsdLogicDetail;
import com.hsd.survey.model.HsdLogicMaster;
import com.hsd.survey.model.HsdModelAnswer;
import com.hsd.survey.model.HsdModelPage;
import com.hsd.survey.model.HsdModelQuestion;
import com.hsd.survey.model.HsdModelSurvey;
import com.hsd.survey.service.ISurveyDesignService;
import com.hsd.survey.util.SurveyUtil;

/**
 * <p>
 * 类描述：问卷设计服务实现类
 * <p>
 * 创建人：Abdi
 * <p>
 * 创建时间：2013-11-3 下午07:26:10
 */
@Service
public class SurveyDesignServiceImpl extends BaseService implements ISurveyDesignService{
	@Autowired
	private ISurveyCommonDao surveyDao;
	
	/**
	 * 获取问卷信息
	 * @param surveyuuid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String getSurveyInfo(String surveyuuid){
		// 1 加载问卷信息
		Map queryMap = new HashMap();
		queryMap.put("surveyuuid", surveyuuid);
		HsdModelSurvey survey = (HsdModelSurvey)surveyDao.getUniqueObject(HsdModelSurvey.class, queryMap);
		
		// 2 获取问题集合
		queryMap.clear();
		queryMap.put("surveyuuid", surveyuuid);
		queryMap.put("isgridchildquestion", 0);
		List<HsdModelQuestion> questionList = surveyDao.findList(HsdModelQuestion.class, queryMap, "sortindex");
		
		// 3 加载问题其他部件
		JSONArray questionsArray = new JSONArray();
		for(HsdModelQuestion modelQuestion : questionList){
			// 问题参数
			JSONObject oneQuestion = JSONObject.fromObject(modelQuestion);
			
			// 加载子问题
			queryMap.clear();
			queryMap.put("fatherquestionuuid", modelQuestion.getQuestionuuid());
			queryMap.put("isgridchildquestion", 1);
			queryMap.put("surveyuuid", surveyuuid);
			List<HsdModelQuestion> childQuestionList = surveyDao.findList(HsdModelQuestion.class, queryMap, "sortindex");
			oneQuestion.put("questions", JSONArray.fromObject(childQuestionList));
			
			// 加载答案模板
			queryMap.clear();
			queryMap.put("surveyuuid", surveyuuid);
			queryMap.put("questionuuid", modelQuestion.getQuestionuuid());
			List<HsdModelAnswer> answerList = surveyDao.findList(HsdModelAnswer.class, queryMap, "sortindex");
			oneQuestion.put("answers", JSONArray.fromObject(answerList));
			
			questionsArray.add(oneQuestion);
		}
		
		queryMap.clear();
		queryMap.put("surveyuuid",surveyuuid);
		List<HsdModelPage> pagelist = surveyDao.findList(HsdModelPage.class, queryMap, "sortindex");
		
		
		JSONObject msg = new JSONObject();
		msg.put("survey", SurveyModelHelper.toDisplaySurvey(survey));
		msg.put("questionlist", SurveyModelHelper.toDisplayQuestion(questionsArray));
		msg.put("pagelist", SurveyModelHelper.toDisplayPage(pagelist));

		JSONObject result = new JSONObject();
		result.put("error", 0);
		result.put("msg", msg);
		return result.toString();
	}
	
	/**
	 * 更新问卷的信息
	 * @param survey
	 * @param pagelist
	 * @param questionlist
	 * @return
	 */
	@Override
	@SuppressWarnings("unchecked")
	public void updateSurveyInfo(String survey,String pagelist,String questionlist){
		JSONObject surveyJsonObj = JSONObject.fromObject(survey);
		String surveyuuid = surveyJsonObj.getString("id");

		// 清空问题、答案、页面
		surveyDao.deleteBeansByProperties(HsdModelPage.class, new String[]{"surveyuuid"},new String[]{surveyuuid});
		surveyDao.deleteBeansByProperties(HsdModelQuestion.class, new String[]{"surveyuuid"},new String[]{surveyuuid});
		surveyDao.deleteBeansByProperties(HsdModelAnswer.class, new String[]{"surveyuuid"},new String[]{surveyuuid});
		
		// 数据库查询问卷信息
		Map query = new HashMap();
		query.put("surveyuuid",surveyuuid);
		
		// 更新页信息
		Map<String,HsdModelPage> pageMap = SurveyModelHelper.refreshPageInfo(pagelist,surveyuuid);
		List<HsdModelPage> pageList = SurveyUtil.transMap2List(pageMap);
		if(null != pageList && pageList.size() >= 1){
			surveyDao.saveOrUpdateAll(pageList);
		}
		
		// 更新问题
		Map<String,List> refleshQuestionMap = SurveyModelHelper.refreshQuestionInfo(questionlist, surveyuuid, pageMap);
		List<HsdModelQuestion> refleshQuestionlist = refleshQuestionMap.get("saveQuestion");
		if(null != refleshQuestionlist && refleshQuestionlist.size() >= 1){
			surveyDao.saveOrUpdateAll(refleshQuestionlist);
		}
		List<HsdModelAnswer> refleshAnswerlist = refleshQuestionMap.get("saveAnswer");
		if(null != refleshAnswerlist && refleshAnswerlist.size() >= 1){
			surveyDao.saveOrUpdateAll(refleshAnswerlist);
		}
		
		HsdModelSurvey modelSurvey = (HsdModelSurvey)surveyDao.getUniqueObject(HsdModelSurvey.class, query);
		modelSurvey.setPagecount(pageList.size());
		modelSurvey.setQuestioncount(null == refleshQuestionlist ? 0 : refleshQuestionlist.size());
		SurveyModelHelper.refreshModelSurvey(modelSurvey,surveyJsonObj);
		surveyDao.save(modelSurvey); // 保存问卷
	}
	
	/**
	 * 更新问卷状态
	 * @param status
	 */
	public void updateSurveyStatus(String surveyuuid,String status){
		surveyDao.executeUpdate("update HsdModelSurvey set status=? where surveyuuid=?", new Object[]{Long.parseLong(status),surveyuuid});
	}

	/**
	 * 保存问卷逻辑
	 * @param surveyuuid
	 * @param logiclist
	 */
	@Override
	public void saveLogic(String surveyuuid, String logiclist) {
		JSONArray logicArray = JSONArray.fromObject(logiclist);
		for(Object logicJson : logicArray){
			JSONObject logicMasterJson = JSONObject.fromObject(logicJson);
			
			// 问卷主逻辑
			HsdLogicMaster logicMaster = new HsdLogicMaster();
			if(SurveyUtil.isUUIDFormat(logicMasterJson.getString("masteruuid"))){ // 已保存过
				//logicMaster.setId();
				logicMaster.setMasteruuid(logicMasterJson.getString("masteruuid"));
				logicMaster.setCreatetime(logicMasterJson.getString("createtime"));
			}else { // 未保存
				logicMaster.setMasteruuid(UUID.randomUUID().toString());
				logicMaster.setCreatetime(DateUtil.currentDateTime());
			}
			logicMaster.setSurveyuuid(logicMasterJson.getString("surveyuuid"));
			logicMaster.setQuestionuuid(logicMasterJson.getString("questionuuid"));
			logicMaster.setFatherquestionuuid(logicMasterJson.getString("fatherquestionuuid"));
			logicMaster.setType(logicMasterJson.getInt("type"));
			logicMaster.setSortindex(logicMasterJson.getInt("sortindex"));
			logicMaster.setPageuuid(logicMasterJson.getString("pageuuid"));
			logicMaster.setAnsweruuid(logicMasterJson.getString("answeruuid"));
			
			surveyDao.save(logicMaster);
			
			// 问卷详情逻辑
			String logicdetails = logicMasterJson.getString("logicdetails");
			JSONArray detailArray = JSONArray.fromObject(logicdetails);
			for(Object detailJson : detailArray){
				JSONObject detailLogicJson = JSONObject.fromObject(detailJson);
				HsdLogicDetail detailLogic = new HsdLogicDetail();
				if(SurveyUtil.isUUIDFormat(detailLogicJson.getString("detailuuid"))){ // 已保存过
					//detailLogic.setId(detailLogicJson.getLong("id"));
					detailLogic.setDetailuuid(detailLogicJson.getString("detailuuid"));
					detailLogic.setCreatetime(detailLogicJson.getString("createtime"));
				}else{
					detailLogic.setDetailuuid(UUID.randomUUID().toString());
					detailLogic.setCreatetime(DateUtil.currentDateTime());
					detailLogic.setModifytime(DateUtil.currentDateTime());
				}
				detailLogic.setLogicuuid(logicMaster.getMasteruuid());
				detailLogic.setCondition(detailLogicJson.getInt("condition"));
				detailLogic.setFatherquestionuuid(detailLogicJson.getString("fatherquestionuuid"));
				detailLogic.setQuestionuuid(detailLogicJson.getString("questionuuid"));
				detailLogic.setAnsweruuid(detailLogicJson.getString("answeruuid"));
				detailLogic.setSortindex(detailLogicJson.getString("sortindex"));
				surveyDao.save(detailLogic);
			}
		}
		System.out.println(logicArray.toString());
	}
	
	@Override
	public IBaseDAO getBaseDao() {
		return surveyDao;
	}
}